import {Component} from 'react';
import {connect} from 'react-redux';
import axios from 'axios';
import * as Notification from 'modules/notification/actions';
import Session from 'modules/auth/session';
import {Button, Icon, PageHeader} from 'antd';
import styled from "styled-components";

const Outer = styled.div`
  border:1px solid #ececec;
  margin:20px;
  position:relative;
  box-shadow: 3px 3px 6px rgba(0,0,0,0.1), 3px 3px 6px rgba(0,0,0,0.2);
`;

const LoadIngDiv = styled.div`
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background:rgba(255,255,255,.6);
  z-index:${p => p.visible ? 9 : 0};
      font-size: 56px;
    display: ${p => p.visible ? 'flex' : 'none'};
    justify-content: center;
    align-items: center;
`;

const Title = styled.div`
  background:#f1f1f1;
  height:50px;
  line-height:50px;
  text-indent:1em;
  color:#333;
  font-weight: bold;
`;

const Conten = styled.div`
  margin:120px 20px;
  box-sizing:border-box;
`;

const Item = styled.div`
  display:flex;
  width:49%;
  margin:10px 0;
  float: left;
`;
const Bold = styled.span`
  font-weight:bold;
`;
const Clear = styled.span`
  clear:both;
      display: block;
    height: 0;
`;
const Inline = styled.span`
  display: inline-block;
    word-break: break-all;
    width: calc( 100% - 130px );
`;
const CenterBtn = styled.div`
  text-align:center;
  padding:20px
`;
const RightImportBox = styled.div`
  position:relative;
  display:inline-block;
  overflow:hidden;
`;

class Collection extends Component {
    state = {
        search: '',
        document: {
            action: '',
            visible: false,
            dimmed: false
        },
        confirm: {
            visible: false,
            imsi: ''
        },
        view: {
            visible: false,
            disableOnClickOutside: false,
            imsi: ''
        },
        visible: false,
        listData: []
    };

    componentWillMount() {

    }

    ImportData = () => {
        const {dispatch} = this.props
        this.setState({
            visible: true
        })
        var $this = this
        var reader = new FileReader();
        let obj = document.getElementById('csvFileInput')
        reader.readAsText(obj.files[0]);
        reader.onload = function () {
            $this.parseDataToSend(this.result)
            setTimeout(function () {
                obj.value = ''
            }, 300)
        }
    }


    parseDataToSend = (string) => {
        const {dispatch} = this.props

        let $this = this
        let allData = {}
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        let getBaseJson = {}
        try {
            getBaseJson = JSON.parse(string)
            console.log(getBaseJson)
        } catch (e) {
            dispatch(Notification.error({
                title: '提示', autoDismiss: 4,
                message: `请上传正确的备份文件文件！`
            }));
            this.setState({
                visible: false
            })
            return false;
        }
        if (getBaseJson.fn != 'encodeURI_btoa') {
            dispatch(Notification.error({
                title: '提示', autoDismiss: 4,
                message: `请上传正确的备份文件文件！`
            }));
            this.setState({
                visible: false
            })
            return false;
        } else {
            let getDataStr = getBaseJson.string
            let getParseString = decodeURI(atob(getDataStr))
            let getParseData = JSON.parse(getParseString)
            console.log(getParseData)
            axios({
                baseURL: '/api/db',
                headers: headers,
                method: "get",
                url: '/amf',
                params: {},
                // data
            }).then(amfsres => {
                getParseData.amfs[0]._id = amfsres.data[0]._id
                axios({
                    baseURL: '/api/db',
                    headers: headers,
                    method: "PATCH",
                    url: '/amf/' + amfsres.data[0]._id,
                    data: getParseData.amfs[0],
                })

                axios({
                    baseURL: '/api/db',
                    headers: headers,
                    method: "get",
                    url: '/dp',
                    params: {},
                    // data
                }).then(dpsres => {
                    getParseData.dps[0]._id = dpsres.data[0]._id
                    getParseData.dps[0].config.dpData = getParseData.dps[0].config.dpData || []
                    axios({
                        baseURL: '/api/db',
                        headers: headers,
                        method: "PATCH",
                        url: '/dp/' + dpsres.data[0]._id,
                        data: getParseData.dps[0],
                    })
                    axios({
                        baseURL: '/api/db',
                        headers: headers,
                        method: "get",
                        url: '/equipmentinfo',
                        params: {},
                        // data
                    }).then(equipmentinfosres => {
                        getParseData.equipmentinfos[0]._id = equipmentinfosres.data[0]._id
                        axios({
                            baseURL: '/api/db',
                            headers: headers,
                            method: "PATCH",
                            url: '/equipmentinfo/' + equipmentinfosres.data[0]._id,
                            data: getParseData.equipmentinfos[0],
                        })
                        axios({
                            baseURL: '/api/db',
                            headers: headers,
                            method: "get",
                            url: '/smf',
                            params: {},
                            // data
                        }).then(smfsres => {
                            getParseData.smfs[0]._id = smfsres.data[0]._id
                            axios({
                                baseURL: '/api/db',
                                headers: headers,
                                method: "PATCH",
                                url: '/smf/' + smfsres.data[0]._id,
                                data: getParseData.smfs[0],
                            })


                            this.setState({
                                visible: false
                            })

                            dispatch(Notification.success({
                                title: '提示',
                                message: `AMF配置、SMF配置、DP配置和设备信息 导入成功！！`,
                                autoDismiss: 5
                            }));

                        })

                    })

                })

            })
        }

    }

    exportData = () => {
        const {dispatch} = this.props
        this.setState({
            visible: true
        })
        let $this = this
        let allData = {}
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/account',
            params: {},
            // data
        }).then(accountsres => {
            allData.accounts = accountsres.data
            axios({
                baseURL: '/api/db',
                headers: headers,
                method: "get",
                url: '/amf',
                params: {},
                // data
            }).then(amfsres => {
                allData.amfs = amfsres.data
                axios({
                    baseURL: '/api/db',
                    headers: headers,
                    method: "get",
                    url: '/dp',
                    params: {},
                    // data
                }).then(dpsres => {
                    allData.dps = dpsres.data
                    axios({
                        baseURL: '/api/db',
                        headers: headers,
                        method: "get",
                        url: '/equipmentinfo',
                        params: {},
                        // data
                    }).then(equipmentinfosres => {
                        allData.equipmentinfos = equipmentinfosres.data
                        axios({
                            baseURL: '/api/db',
                            headers: headers,
                            method: "get",
                            url: '/smf',
                            params: {},
                            // data
                        }).then(smfsres => {
                            allData.smfs = smfsres.data
                            let getObj = {
                                fn: 'encodeURI_btoa',
                                string: btoa(encodeURI(JSON.stringify(allData)))
                            }
                            this.exportWithString(JSON.stringify(getObj))
                        })


                        // axios({
                        //     baseURL: '/api/db',
                        //     headers: headers,
                        //     method: "get",
                        //     url: '/profile',
                        //     params: {},
                        //     // data
                        // }).
                        // then(profilesres => {
                        //     allData.profiles = profilesres.data
                        //
                        //     axios({
                        //         baseURL: '/api/db',
                        //         headers: headers,
                        //         method: "get",
                        //         url: '/smf',
                        //         params: {},
                        //         // data
                        //     }).then(smfsres => {
                        //         allData.smfs = smfsres.data
                        //
                        //         axios({
                        //             baseURL: '/api/db',
                        //             headers: headers,
                        //             method: "get",
                        //             url: '/subscriber',
                        //             params: {},
                        //             // data
                        //         }).then(subscribersres => {
                        //
                        //             allData.subscribers = subscribersres.data
                        //             let getObj = {
                        //                 fn: 'encodeURI_btoa',
                        //                 string: btoa(encodeURI(JSON.stringify(allData)))
                        //             }
                        //             this.exportWithString(JSON.stringify(getObj))
                        //         })
                        //
                        //     })
                        // })

                    })

                })

            })
        })


    }

    exportWithString = (CVSString) => {
        const {dispatch} = this.props
        var $this = this
        var msieversion = function () {
            var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE ");
            if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
            {
                return true;
            } else { // If another browser,
                return false;
            }
            return false;
        };

        function formatDate(now) {
            var year = now.getFullYear();
            var month = now.getMonth() + 1;
            var date = now.getDate();
            var hour = now.getHours();
            var minute = now.getMinutes();
            var second = now.getSeconds();
            return year + "-" + month + "-" + date + "~" + hour + "_" + minute + "_" + second;
        }

        var fileName = "系统配置文件" + formatDate(new Date());
        if (msieversion()) {
            var IEwindow = window.open();
            IEwindow.document.write('sep=,\r\n' + CVSString);
            IEwindow.document.close();
            IEwindow.document.execCommand('SaveAs', true, fileName + ".data");
            IEwindow.close();
        } else {
            //var uri = 'data:application/csv;charset=utf-8,' + escape(CSV);
            var uri = 'data:application/data;charset=utf-8,' + CVSString;
            var link = document.createElement("a");
            link.href = uri;
            link.style = "visibility:hidden";
            link.download = fileName + ".data";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        this.setState({
            visible: false
        })

        dispatch(Notification.success({
            title: '提示',
            message: `已成功导出系统所有数据！`
        }));
    }


    render() {
        let $this = this
        return (
            <div>
                <PageHeader
                    style={{
                        border: '1px solid rgb(235, 237, 240)',
                    }}
                    title="配置文件管理"
                />
                <Outer>
                    <LoadIngDiv visible={this.state.visible}>
                        <div style={{textAlign: 'center'}}>
                            <Icon type="loading"/>
                            <div style={{fontSize: '16px', color: '#666', marginTop: '20px'}}>程序处理中,请耐心等待...</div>
                        </div>
                    </LoadIngDiv>
                    <Conten>

                        <CenterBtn>
                            <RightImportBox>
                                <Button size={'large'} type="primary" onClick={this.exportData}>
                                    <Icon type="cloud-download"/> 导出配置文件
                                </Button>
                            </RightImportBox>

                            <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                            <RightImportBox>
                                <Button size={'large'} type="primary" ghost>
                                    <Icon type="cloud-upload"/> 导入配置文件
                                </Button>
                                <input type="file" className={'inputImportBtns'} id="csvFileInput"
                                       onChange={(e) => this.ImportData(e)}/>
                            </RightImportBox>


                        </CenterBtn>

                    </Conten>
                </Outer>


            </div>
        )
    }
}

Collection = connect(
    (state) => ({})
)(Collection);

export default Collection;